package org.hongqi.common.senpec.base.spring.security.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.hongqi.common.senpec.sys.user.User;
import org.springframework.stereotype.Service;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Service
public class JWTService {
    private static final String SECRET_KEY = "5368566D597133743677397A244326452948404D635166546A576E5A72347537";

    public String generateToken(Map<String, Object> extraClaims, User user) {
        return Jwts.builder()//
                .setClaims(extraClaims)//
                .setSubject(user.getUsername())//
                .setIssuedAt(new Date(System.currentTimeMillis()))//
                .setExpiration(new Date(System.currentTimeMillis() + 14 * 24 * 60 * 60 * 1000))//
                .signWith(getSigningKey(), SignatureAlgorithm.HS256)//
                .compact();
    }

    @SuppressWarnings("ALL")
    public String generateToken(User user) {
        return generateToken(new HashMap<>(), user);
    }

    public boolean isTokenValid(String token, User user) {
        final String username = extractUsername(token);
        return (username.equals(user.getUsername())) && !isTokenExpired(token);
    }

    public boolean isTokenExpired(String token) {
        return extractExpiration(token).before(new Date());
    }


    private Claims extractAllClaims(String token) {
        return Jwts.parserBuilder()//
                .setSigningKey(getSigningKey())//
                .build()//
                .parseClaimsJws(token)//
                .getBody();
    }

    private Key getSigningKey() {
        byte[] keyBytes = Decoders.BASE64.decode(SECRET_KEY);
        return Keys.hmacShaKeyFor(keyBytes);
    }


    public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = extractAllClaims(token);
        return claimsResolver.apply(claims);
    }

    public String extractUsername(String token) {
        return extractClaim(token, Claims::getSubject);
    }

    public Date extractExpiration(String token) {
        return extractClaim(token, Claims::getExpiration);
    }

    @SuppressWarnings("ALL")
    public Long extractUserId(String token) {
        String userIdStr = extractClaim(token, Claims::getId);
        return Long.parseLong(userIdStr);
    }

}
